package com.ifast.asset.controller;


import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;

import com.alibaba.fastjson.JSON;
import com.ifast.asset.Thread.SetAssetStatus;
import com.ifast.asset.domain.Assets;
import com.ifast.asset.domain.SegmentDO;
import com.ifast.asset.domain.TaskrecordDO;
import com.ifast.asset.service.AssetsService;
import com.ifast.asset.service.SegmentService;
import com.ifast.asset.service.TaskrecordService;
import com.ifast.asset.util.IpUtil;
import com.ifast.asset.util.IpUtils;
import com.ifast.asset.util.ThreadPoolUtil;
import com.ifast.common.config.Constant;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ifast.common.annotation.Log;
import com.ifast.common.base.BaseController;
import com.ifast.common.utils.Result;

/**
 * <pre>
 *
 * </pre>
 * <small> 2021-03-14 14:23:19 | Aron</small>
 */
@Controller
@RequestMapping("/wxmp/segment")
public class SegmentController extends BaseController {
    @Autowired
    private SegmentService segmentService;
    @Autowired
    private AssetsService assetsService;
    @Autowired
    private TaskrecordService taskrecordService;

    @GetMapping()
        //@RequiresPermissions("wxmp:segment:segment")
    String Segment() {
        return "wxmp/segment/segment";
    }

    @ResponseBody
    @GetMapping("/list")
    //@RequiresPermissions("wxmp:segment:segment")
    public Result<Page<SegmentDO>> list(SegmentDO segmentDTO) {
        Wrapper<SegmentDO> wrapper = new EntityWrapper<>(segmentDTO).orderBy("id", false);
        Page<SegmentDO> page = segmentService.selectPage(getPage(SegmentDO.class), wrapper);
        return Result.ok(page);
    }

    @GetMapping("/add")
        //@RequiresPermissions("wxmp:segment:add")
    String add() {
        return "wxmp/segment/add";
    }

    @GetMapping("/edit/{id}")
        //@RequiresPermissions("wxmp:segment:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        SegmentDO segment = segmentService.selectById(id);
        model.addAttribute("segment", segment);
        return "wxmp/segment/edit";
    }

    @Log("添加")
    @ResponseBody
    @PostMapping("/save")
    //@RequiresPermissions("wxmp:segment:add")
    public Result<String> save(SegmentDO segment) {
        segmentService.insert(segment);
        return Result.ok();
    }

    @Log("修改")
    @ResponseBody
    @RequestMapping("/update")
    //@RequiresPermissions("wxmp:segment:edit")
    public Result<String> update(SegmentDO segment) {
        boolean update = segmentService.updateById(segment);
        return update ? Result.ok() : Result.fail();
    }

    @Log("删除")
    @PostMapping("/remove")
    @ResponseBody
    //@RequiresPermissions("wxmp:segment:remove")
    public Result<String> remove(Integer id) {
        segmentService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除")
    @PostMapping("/batchRemove")
    @ResponseBody
    //@RequiresPermissions("wxmp:segment:batchRemove")
    public Result<String> remove(@RequestParam("ids[]") Integer[] ids) {
        segmentService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }

    //定时检测  资产列表中的设备  开关机状态
    @Scheduled(cron = "0 00 23 * * ? ")   //0 0 0 * * ? （每日零点） 0 59 15 * * ?
    public void checkOpenOrDown() {

        System.out.println("开始执行检测设备是否开关机函数");
        Thread thread = new Thread() {
            @Override
            public void run() {

                //获取资产列表
                List<Assets> assets = assetsService.selectList(null);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //查询每个设备是否  开机
                for (int i = 0; i < assets.size(); i++) {

                    boolean falg = IpUtil.ping(assets.get(i).getIp());
                    if (falg) {
                        //ping的通说明设备在线
                        SegmentDO segment = new SegmentDO();
                        segment.setIp(assets.get(i).getIp());
                        //判断是否存在 次ip的记录
                        Wrapper w = new EntityWrapper(segment);
                        if (segmentService.selectOne(w)==null){
                            segment.setStatus("1");
                            segment.setTime(simpleDateFormat.format(new Date()));
                            segmentService.insert(segment);
                        }else {
                            segment.setId(segmentService.selectOne(w).getId());
                            segment.setStatus("1");
                            segment.setTime(simpleDateFormat.format(new Date()));
                            segmentService.updateAllColumnById(segment);
                        }

                    } else {
                        //ping不通说明设备不在线
                        SegmentDO segment = new SegmentDO();
                        segment.setIp(assets.get(i).getIp());
                        Wrapper w = new EntityWrapper(segment);
                        if (segmentService.selectOne(w)==null){

                            segment.setStatus("0");
                            segment.setTime(simpleDateFormat.format(new Date()));
                            segmentService.insert(segment);
                        }else {
                            segment.setId(segmentService.selectOne(w).getId());
                            segment.setStatus("0");
                            segment.setTime(simpleDateFormat.format(new Date()));
                            segmentService.updateAllColumnById(segment);
                        }
                    }
                }
            }
        };
        thread.start();
    }

    @GetMapping("/getEquipment")
    @ResponseBody
    //筛选一个网段中 的各个设备信息   返回信息中status 1：已开机   0: 关机   2：未产生记录
    public Result<Object> getEquipment(String ipSegment) {
        List<Map<String, Object>> equipments = new ArrayList<>();
        if (ipSegment.contains("/")) {
            String[] ipAndMask = ipSegment.split("/");
            //获取ip段内所有的ip地址
            List<String> lists = IpUtils.parseIpMaskRange(ipAndMask[0], ipAndMask[1]);

            for (int i = 0; i < lists.size(); i++) {

                //Assets assets = new Assets();
                Wrapper assetwrapper = new EntityWrapper();
                assetwrapper.eq("ip",lists.get(i));
                Assets assets = assetsService.selectOne(assetwrapper);
                //判断ip是否此时是开机状态
                Wrapper wrapper = new EntityWrapper();
                wrapper.eq("ip", lists.get(i)).orderBy("time", false);
                SegmentDO segmentDO = segmentService.selectOne(wrapper);
                if (segmentDO!=null){

                    Map<String,Object>map = new HashMap<>();
                    map.put("status",segmentDO.getStatus());
                    map.put("ip",segmentDO.getIp());
                    map.put("level",getLevel(assets.getScore()));
                    map.put("id",assets.getId());
                    equipments.add(map);
                }else {
                    Map<String,Object>map = new HashMap<>();
                    map.put("status",2);//状态2时未产生记录
                    map.put("ip",lists.get(i));
                    map.put("level",getLevel(0));
                    //map.put("id",assets.getId());
                    equipments.add(map);
                }
            }
        }
        return Result.ok(equipments);
    }

    public String getLevel(double score){

        if (score>=95&&score<=100){
            return "1";
        }else if(score>=80&&score<95){

            return "2";
        }else if(score>=65&&score<80){

            return "3";
        }else if(score>=45&&score<65){
            return "4";
        }else {
            return "0";
        }
    }

    //定时函数  讲1个小时以上还未解决的任务  设定状态为-1 未完成
    @Scheduled(cron = "0 0/5 * * * ? ")
    public void setAssetStatus() {

        ExecutorService executorService = ThreadPoolUtil.getCachedThreadPool();
        executorService.submit(new SetAssetStatus(taskrecordService));
    }
    //工具类判断是否含有此ip的资产
    public int IsExist(String ip){

        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("ip",ip);
        if(assetsService.selectCount(wrapper) > 0){

            return 1;
        }else {
            return 0;
        }

    }
}
